package cn.edu.klmy.dao.impl;

import cn.edu.klmy.dao.AbstractJdbcTemplate;
import cn.edu.klmy.dao.IAuthenticationDao;
import cn.edu.klmy.models.user.AuthenticationUser;
import com.googlecode.ehcache.annotations.*;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 认证实现类
 *
 * @author 顾伟
 *         创建日期：13-3-29
 */
@Repository
public class AuthenticationDao extends AbstractJdbcTemplate implements IAuthenticationDao {

    /**
     * 通过用户名称获取用户
     *
     * @param userIdNo 用户身份证号
     * @return 用户对象实例
     */
    @Override
    @Cacheable(cacheName = "userCache",
            keyGenerator = @KeyGenerator(
                    name = "ListCacheKeyGenerator",
                    properties = @Property(name = "includeMethod", value = "false")
            )
    )
    public AuthenticationUser getUserByUserName(String userIdNo) {
        //判断用户身份
        String USER_QUERY = "SELECT ID,USER_NAME,USER_TYPE,USER_PASSWORD,USER_ID_NO FROM USER WHERE USER_ID_NO=?";
        AuthenticationUser user = (AuthenticationUser) this.jdbcTemplate.queryForObject(USER_QUERY, new Object[]{userIdNo}, new UserRowMapper());
        return user;
    }

    /**
     * 更新用户密码
     *
     * @param userIdNo 用户身份证号
     * @param password 待更新的用户密码
     * @return 成功与否
     */
    @Override
    @TriggersRemove(cacheName = "userCache", when = When.AFTER_METHOD_INVOCATION,
            keyGenerator = @KeyGenerator(
                    name = "ListCacheKeyGenerator",
                    properties = @Property(name = "includeMethod", value = "false")
            )
    )
    public boolean updatePasswordByUserId(@PartialCacheKey String userIdNo, String password) {
        String PASSWORD_UPDATE = "UPDATE USER SET USER_PASSWORD=? WHERE USER_ID_NO=?";
        int updateCount = this.jdbcTemplate.update(PASSWORD_UPDATE, new Object[]{password, userIdNo});
        if (updateCount == 0) {
            return false;
        }
        return true;
    }

    /**
     * 登录用户基础信息映射
     */
    private class UserRowMapper implements RowMapper {
        @Override
        public Object mapRow(ResultSet resultSet, int i) throws SQLException {
            AuthenticationUser user = new AuthenticationUser();
            user.setUserId(resultSet.getInt("ID"));
            user.setUserName(resultSet.getString("USER_NAME"));
            user.setUserPassword(resultSet.getString("USER_PASSWORD"));
            user.setUserType(resultSet.getInt("USER_TYPE"));
            user.setUserIdNo(resultSet.getString("USER_ID_NO"));
            return user;
        }
    }


}
